// 经纬度
var lat = false;
var long = false;

//地图所需变量
var center = {};
var map = {};
var infoWin = {};

//门店列表
var shop_list = [];

//要分享的店铺id
var share_shop_index=false;

$(function() {
    resertWindow();
    $(window).resize(function() {
        resertWindow();
    });

    //绑定分享遮罩和取消点击影藏事件
    // $('.share-zhezhao').click(function(){
    //     $(".share-box").animate({bottom:'-200px'},function(){
    //         $('.share-zhezhao').hide();
    //     });
    // });
    // $('.share-cancel').click(function(){
    //     $(".share-box").animate({bottom:'-200px'},function(){
    //         $('.share-zhezhao').hide();
    //     });
    // });

    // 列表地图初始化,分享内容初始化
    doDefault(function(){
        getLocation();
        deShareDefault();
    },getShopList);

    //分享数据初始化
    $('.share-zhezhao').click(function(){
        shareDefault();
    });


    //绑定切换列表地图模式按钮
    $('.show-type-name').click(function() {
        $('.show-type-line').hide();
        $(this).next().show();
        $('.show-type-content').hide();
        $('.show-type-content').eq($(this).attr('data-index')).show();
        getShopList();
    });

    $('.remove-param').click(function(){
        $(this).prev().val('');
    });
    $('.search-button button').click(function(){
        getShopList();
    });
})

function resertWindow() {
    $('.shop-list').height(Number($(window).height()) - 250);
    $('.shop-map').height(Number($(window).height()) - 260);
    $('.share-zhezhao').height(Number($(window).height())).width(Number($(window).width()));
}

//获取门店列表
function getShopList() {
    $('.shop-list').html('');
    $('.shop-map').html('');
    $('.icon-spinner').show();
    $.ajax({
        type: "post",
        url: "Api/Shop/getShopList",
        data: {
            park_id:$('#park_id').val(),
            param:$('.param').val(),
            long:long,
            lat:lat
        },
        async: true,
        dataType: 'json',
        success: function(data) {
            if (data.status) {
                $('.icon-spinner').hide();
                var t = JSON.parse(data.v);
                shop_list = t;
                $.each(shop_list, function(k, v) {
                    $('.shop-list-item-demo .shop-name').html(sub_str(v.name, 15));
                    $('.shop-list-item-demo .shop-share u').attr('data-index',k);
                    
                    $('.shop-list-item-demo .shop-address lable').html(sub_str(v.address, 20));
                    //计算距离
                    if ((!lat) || (!long)) {
                        $('.shop-list-item-demo .shop-length u').html('??km');
                    } else {
                        $('.shop-list-item-demo .shop-length u').html(getDistance(v.lat, v.long, lat, long) + 'km');
                    }
                    $('.shop-list-item-demo .leave-msg').attr('href',getRootPath()+'/Home/Shop/leaveMsg?park_id='+$('#park_id').val());
                    $('.shop-list-item-demo .shop-info').attr('data-id', v.id);
                    $('.shop-list').append($('.shop-list-item-demo').html());
                });
                mapInit(shop_list);
            } else {

            }
        }
    });
}


//获取微信jssdk凭证
function doDefault(successCallBack,errorCallBack) {
    var successCallBack=successCallBack||false; 
    var errorCallBack=errorCallBack||false; 
    $.ajax({
        type: "post",
        url: "CommonApi/CommonWx/getWxJsSdkConfig",
        data: {
            url: window.location.href,
            park_id:$('#park_id').val()
        },
        async: true,
        dataType: 'json',
        success: function(data) {
            if (data.status) {
                var t = JSON.parse(data.v);
                wx.config({
                    beta: true,
                    debug: false,
                    appId: t.appId,
                    timestamp: t.timestamp,
                    nonceStr: t.nonceStr,
                    signature: t.signature,
                    jsApiList: ['checkJsApi', 'openLocation', 'getLocation',"onMenuShareTimeline", "onMenuShareAppMessage"] // 必填，需要使用的JS接口列表
                });
                if(successCallBack){
                    successCallBack();
                }
            } else {
                errorAlert(data.msg);
                if(errorCallBack){
                    errorCallBack();
                }
            }
        }
    });
}
var getLocation = function() {
    wx.ready(function() {
        wx.checkJsApi({
            jsApiList: ['getLocation'], // 需要检测的JS接口列表，所有JS接口列表见附录2,  
            success: function(res) {
                if (res.checkResult.getLocation == false) {
                    errorAlert("您的微信版本太低！");
                    return;
                }
            }
        });
        wx.getLocation({
            type: 'gcj02',
            success: function(res) {
                lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                long = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                getShopList();
            },
            fail: function(e) {
                errorAlert("未能获取地理位置信息");
                getShopList();
            },
            cancel: function(res) {
                errorAlert("未能获取地理位置");
                getShopList();
            }
        });
    });
};



//地图
function mapInit(shop) {
    // alert($('#map_mark').val());
    center = new qq.maps.LatLng(lat, long);
    map = new qq.maps.Map(document.getElementById("shop-map"), {
        center: center,
        zoom: 15
    });
    infoWin = new qq.maps.InfoWindow({
        map: map
    });


    var latlngs = [
        new qq.maps.LatLng(lat, long),
    ];
    $.each(shop, function(k, v) {
        latlngs.push(new qq.maps.LatLng(v.lat, v.long));
    });


    for (var i = 0; i < latlngs.length; i++) {
        (function(n) {

            var marker = new qq.maps.Marker({
                position: latlngs[n],
                map: map
            });
            if (n != 0) {
                var anchor = new qq.maps.Point(20, 39),
                    size = new qq.maps.Size(54, 80),
                    origin = new qq.maps.Point(0, 0),
                    icon = new qq.maps.MarkerImage(
                        getRootPath() + ($('#map_mark').val()==''?"/public/home/images/mark-1.png":'/'+$('#map_mark').val()),
                        size,
                        origin,
                        anchor
                    );
                marker.setIcon(icon);
            }
            marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
            qq.maps.event.addListener(marker, 'click', function() {
                infoWin.open();
                if (n == 0) {
                    infoWin.setContent('<div class="shop-box">当前位置</div>');
                } else {
                    infoWin.setContent('<div class="shop-box"><div>' + sub_str(shop[n - 1].name, 20) + '</div><button class="map-shop-info" data-id="'+shop[n - 1].id+'" onclick="shopInfo(this)">店铺详情</button></div>');
                }
                infoWin.setPosition(latlngs[n]);
            });
        })(i);
    }
}


function shopInfo(obj) {
    location.href = getRootPath() + "/Home/Shop/shop?shop=" + $(obj).attr('data-id')+'&park_id='+$('#park_id').val();
}


function shareDefault(){
    share_shop_index=false;
    doDefault(deShareDefault);
}
function shareShop(obj){
    // $('.share-zhezhao').show();
    // $(".share-box").animate({bottom:'0px'});
    share_shop_index=$(obj).attr('data-index');
    doDefault(doShareFriend);
}


var deShareDefault=function(){
    wx.ready(function() {
        wx.checkJsApi({
            jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'], // 需要检测的JS接口列表，所有JS接口列表见附录2,  
            success: function(res) {
                if (res.checkResult.onMenuShareAppMessage == false) {
                    errorAlert("您的微信版本太低！");
                    return;
                }
            }
        });
        $('.share-zhezhao').hide();
        $('.share-arrow').hide();
        wx.onMenuShareAppMessage({
            title: '授权展厅', // 分享标题
            desc: '授权展厅', // 分享描述
            link: window.location.href, // 分享链接
            imgUrl: '', // 分享图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // rightAlert('分享成功');
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareTimeline({
            title:'授权展厅', // 分享标题
            desc: '授权展厅', // 分享描述
            link: window.location.href, // 分享链接
            imgUrl: '', // 分享图标
            success: function () {
                // rightAlert('分享成功');
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
    });
}

var doShareFriend=function(){
    wx.ready(function() {
        wx.checkJsApi({
            jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'], // 需要检测的JS接口列表，所有JS接口列表见附录2,  
            success: function(res) {
                if (res.checkResult.onMenuShareAppMessage == false) {
                    errorAlert("您的微信版本太低！");
                    return;
                }
            }
        });
        $('.share-zhezhao').show();
        $('.share-arrow').show();
        wx.onMenuShareAppMessage({
            title: shop_list[share_shop_index].name, // 分享标题
            desc: shop_list[share_shop_index].address, // 分享描述
            link: getRootPath() + "/Home/Shop/shop?shop=" + shop_list[share_shop_index].id+'&park_id='+$('#park_id').val(), // 分享链接
            imgUrl: getRootPath() +'/'+ shop_list[share_shop_index].img, // 分享图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                shareDefault();
                // rightAlert('分享成功');
            },
            cancel: function () {
                shareDefault();
            }
        });
        wx.onMenuShareTimeline({
            title: shop_list[share_shop_index].name, // 分享标题
            desc: shop_list[share_shop_index].address, // 分享描述
            link: getRootPath() + "/Home/Shop/shop?shop=" + shop_list[share_shop_index].id+'&park_id='+$('#park_id').val(), // 分享链接
            imgUrl: getRootPath() +'/'+ shop_list[share_shop_index].img, // 分享图标
            success: function () {
                shareDefault();
                // rightAlert('分享成功');
            },
            cancel: function () {
                shareDefault();
            }
        });
    });
}
